const express = require('express')
const app = express()
const { MongoClient, ObjectId } = require('mongodb')

let client = null
const dbName = 'test'
function initMongoDB () {
    const url = 'mongodb://localhost:27017'
    client = new MongoClient(url)
}
initMongoDB()

app.use(express.json())

// 注册接口
app.post('/register',
    // 数据校验 express-validator
    async function (req, res, next) {
        try {
            // 数据校验
            // 处理逻辑
            await client.connect()
            const testloginCollection = client.db(dbName).collection('testlogin')
            let body = {
                ...req.body,
            }
            let result = await testloginCollection.insertOne(body)
            console.log(req.body, result)
            res.send({
                code: 200,
                data: result
            })
        } catch (err) {
            next(err)
        }

    })

// 登录接口
app.post('/login',
    // 数据校验 express-validator
    async function (req, res, next) {
        try {
            console.log(req.body)
            // res.send('login')

            // 处理逻辑
            await client.connect()
            const testloginCollection = client.db(dbName).collection('testlogin')
            let body = {
                ...req.body,
            }
            let result = await testloginCollection.findOne(body)
            if (result) {
                console.log(req.body, result)
                delete result.password
                let data = result
                res.send({
                    code: 200,
                    data
                })
            } else {
                res.send({
                    code: 404,
                    data: '未找到到该用户， 可能用户名或密码错误'
                })
            }

        } catch (err) {
            next(err)
        }
    })

// 用户查询接口
app.get('/:id',
    // 数据校验 express-validator
    async function (req, res, next) {
        try {
            console.log(req.params)
            // 处理逻辑
            await client.connect()
            const testloginCollection = client.db(dbName).collection('testlogin')
            const result = await testloginCollection.findOne({
                _id: ObjectId(req.params.id)
            })
            delete result.password
            let data = result
            if (result) {
                res.send({
                    code: 200,
                    data
                })
            } else {
                res.send({
                    code: 404,
                    data: '未查询到该用户'
                })
            }

        } catch (err) {
            next(err)
        }
    })

// 写在所有路由和中间件之后
app.use((err, req, res, next) => {
    res.status(500).json({
        error: err.message
    })
})


app.listen(3005)